package pers.wwz.study.shardingjdbc.config;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

public class ModPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Long> {
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {
        //1、简单的取模方式
//        return shardingValue.getLogicTableName()+"_"+shardingValue.getValue()%2;

        //2、一致性哈希思路,这里用到的表映射的哈希值，可以存放在redis等缓存中间件里面，该方法方便扩展
        long suffix = shardingValue.getValue()%65535;
        if(suffix<16384 || (suffix>=32768 && suffix<49152)) {
            return shardingValue.getLogicTableName()+"_1";
        }else {
            return shardingValue.getLogicTableName()+"_2";
        }
    }
}
